package com.itfreer.arcgis.edit;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.itfreer.arcgis.draw.DrawCommand;
import com.itfreer.arcgis.draw.DrawToolManager;
import com.itfreer.arcgis.layer.LayerLoader;
import com.itfreer.arcgis.query.GetSelectFeatureListener;
import com.itfreer.arcgis.utils.FeatureTableUtils;
import com.itfreer.arcgis.utils.LayerUtils;
import com.itfreer.gis.datasyn.entity.ProjectEntity;
import com.itfreer.gis.datasyn.sub.EditLogService;
import com.itfreer.utils.common.ToastUtils;
import com.itfreer.utils.config.ConfigManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

/**
 * 面分割
 */
class SplitSelectPolygonFeatureCommand implements DrawCommand {

    @Override
    public void Execute(Map<String,Object>params) {
        if (DrawToolManager.GetCurrentTool() == null) {
            ToastUtils.showShort(ConfigManager.getContext(), "当前无编辑操作！");
            return;
        }
        FeatureLayer featureLayer = EditToolUtils.getCurrentEditFeatureLayer();
        if (featureLayer != null) {
            LayerUtils.GetSelectFeature(featureLayer, new GetSelectFeatureListener() {
                @Override
                public void execute(FeatureLayer featureLayer, ListenableFuture<FeatureQueryResult> features) {
                    try {
                        List<Feature> selectFeatues = new ArrayList<>();
                        for (Feature feature : features.get())
                            selectFeatues.add(feature);

                        if (selectFeatues.size() > 1)
                            ToastUtils.showLong(ConfigManager.getContext(), "请选择单个要素进行分割！");
                        else if (selectFeatues.size() == 0)
                            ToastUtils.showLong(ConfigManager.getContext(), "请选择一个面要素！");
                        else {
                            ProjectEntity config = LayerLoader.instance.getConfig(featureLayer);
                            Feature selectFeature  = selectFeatues.get(0);
                            Geometry geometry = DrawToolManager.GetCurrentTool().GetGeometry();
                            if (geometry == null || geometry.isEmpty()) {
                                return;
                            }
                            geometry = GeometryEngine.project(geometry, selectFeature.getGeometry().getSpatialReference());
                            List<Geometry> geometries = GeometryEngine.cut(selectFeature.getGeometry(), (Polyline) geometry);
                            if (geometries != null && geometries.size() > 1) {
                                // 保留最大的图形为之前要素的图形，其他的geometry 作为新增使用
                                Geometry maxGeometry = geometries.get(0);
                                Integer index = 0;
                                for (Integer i = 1; i < geometries.size(); i++) {
                                    if (GeometryEngine.area((Polygon) geometries.get(i)) > GeometryEngine.area((Polygon) maxGeometry)) {
                                        maxGeometry = geometries.get(i);
                                        index = i;
                                    }
                                }
                                selectFeature.setGeometry(maxGeometry);
                                // 需改造
                                ValueOption.updateArea(featureLayer, "MIAN_JI", selectFeature.getAttributes(), maxGeometry);

                                Object osguid = selectFeature.getAttributes().get("SGUID");
                                if(osguid!=null){
                                    EditLogService.instance.editLog(config, osguid.toString());
                                }

                                FeatureTableUtils.UpdateFeature(selectFeature.getFeatureTable(), selectFeature);
                                for (Integer i = 0; i < geometries.size(); i++) {
                                    if (i != index){
                                        Map<String, Object> attribute = new HashMap<>();
                                        String sguid = UUID.randomUUID().toString().replace("-", "");
                                        attribute.put("SGUID", sguid);
                                        // 添加默认值
                                        ValueOption.setDefultValue(featureLayer, attribute, config);
                                        // 需改造
                                        ValueOption.updateArea(featureLayer, "MIAN_JI", attribute, geometries.get(i));

                                        FeatureTableUtils.AddFeature(geometries.get(i), attribute, selectFeature.getFeatureTable());
                                        // 记录日志
                                        EditLogService.instance.addLog(config, sguid);
                                    }
                                }
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                    finally {
                        DrawToolManager.GetCurrentTool().Clear();
                        featureLayer.clearSelection();
                    }
                }
            });
        }
    }
}